<!-- 车次提货记录 -->
<template>
  <div
    class="train_pick_up_record"
    v-if="!appStore.isPhone">
<!--    <SearchCard-->
<!--        ref="searchCardRef"-->
<!--        :searchTemplate="searchTemplate"-->
<!--        :more="false"-->
<!--        @reset="getList"-->
<!--        @search="(data) => getList(data)" />-->
    <el-card
      class="search_card"
      ref="searchCardRef">
      <el-form
        :model="formData"
        :rules="formRules"
        class="search_form">
        <el-row>
          <el-form-item label="提货主体公司">
            <el-select
              v-model="formData.baseCompanyId"
              placeholder="提货主体公司"
              style="width: 130px"
              clearable>
              <el-option
                v-for="item in baseCompanyList"
                :key="item.id"
                :label="item.simple_name"
                :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="资金仓库名称">
            <el-select
              v-model="formData.baseCapitalWarehouseId"
              placeholder="资金仓库名称"
              style="width: 130px"
              clearable>
              <el-option
                v-for="item in capitalWareHouseList"
                :key="item.id"
                :label="item.name"
                :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item
            label="提货人"
            v-if="isExpand">
            <el-select
              v-model="formData.pickUserId"
              placeholder="提货人"
              style="width: 130px"
              clearable>
              <el-option
                v-for="item in userList"
                :key="item.id"
                :label="item.realName"
                :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item
            label="提货日期"
            v-if="isExpand">
            <el-date-picker
              style="width: 230px"
              v-model="selectTime"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              type="daterange"
              range-separator="-"
              start-placeholder="开始时间"
              end-placeholder="结束时间" />
          </el-form-item>
          <el-form-item label="启用状态">
            <el-select
              v-model="formData.isEnable"
              placeholder="启用状态"
              style="width: 130px"
              clearable>
              <el-option
                :label="config.button.text.enable"
                :value="true" />
              <el-option
                label="作废"
                :value="false" />
            </el-select>
          </el-form-item>
          <el-button
            type="primary"
            :style="{ 'margin-left': isExpand ? '0' : '50px' }"
            @click="getList(formData)">
            <template #icon>
              <el-icon>
                <search />
              </el-icon>
            </template>
            {{ config.button.text.query }}
          </el-button>
          <el-button @click="reset">
            <template #icon>
              <el-icon>
                <Refresh />
              </el-icon>
            </template>
            {{ config.button.text.reset }}
          </el-button>
          <div
            class="expanded"
            @click="isExpand = !isExpand">
            <span v-if="!isExpand">
              <span>展开</span>
              <el-icon>
                <ArrowDown />
              </el-icon>
            </span>
            <span v-else>
              <span>收起</span>
              <el-icon>
                <ArrowUp />
              </el-icon>
            </span>
          </div>
        </el-row>
      </el-form>
    </el-card>
    <el-card class="table_card">
      <Table
        :selection-change="handleSelectionChange"
        :data="tableData"
        v-loading="tableLoading"
        :height="height">
        <el-table-column
          type="selection"
          fixed
          width="40"
          align="center" />
        <el-table-column
          prop="baseCompanySimpleName"
          show-overflow-tooltip
          width="120"
          label="提货主体公司" />
        <el-table-column
          prop="baseCapitalWarehouseName"
          show-overflow-tooltip
          width="120"
          label="资金仓库名称" />
        <el-table-column
          prop="baseRiceBarnGoodsSimpleName"
          show-overflow-tooltip
          width="120"
          label="商品简称" />
        <el-table-column
          prop="purchaseOrderName"
          show-overflow-tooltip
          width="120"
          label="采购订单名称" />
        <el-table-column
          prop="pickUserRealName"
          show-overflow-tooltip
          label="提货人" />
        <el-table-column
          prop="pickDate"
          show-overflow-tooltip
          label="提货日期"
          width="130">
          <template #default="scope">
            {{ formatDate(scope.row.pickDate) }}
          </template>
        </el-table-column>
        <el-table-column
          prop="trainNumber"
          show-overflow-tooltip
          label="车次号" />
        <el-table-column
          prop="pickIntactTon"
          show-overflow-tooltip
          width="120"
          label="提货完整吨数" />
        <el-table-column
          prop="pickWornTon"
          show-overflow-tooltip
          width="120"
          label="提货破损吨数" />
        <el-table-column
          prop="pickPayPrice"
          show-overflow-tooltip
          width="100"
          label="提货应付款" />
        <el-table-column
          prop="isEnable"
          show-overflow-tooltip
          width="100"
          label="是否启用">
          <template #default="scope">
            <el-switch
              v-model="scope.row.isEnable"
              inline-prompt
              active-text="启用"
              inactive-text="作废"
              @change="(val) => changeState(val, scope.row)" />
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          fixed="right"
          width="100">
          <template #default="scope">
            <el-button
              type="success"
              @click="viewEvent(scope.row)">
              {{ config.button.text.view }}
            </el-button>
          </template>
        </el-table-column>
      </Table>
      <Pagination
        :pageNum="pageNum"
        :pageSize="pageSize"
        :total="total"
        @handle-size-change="(val) => pageSize = val"
        @handle-current-change="(val) => pageNum = val" />
      <div class="btn-bottom">
        <el-button
          v-permission="validateButtonPermission(route, 6)"
          @click="getBillLading"
          type="warning">
          生成提货单
        </el-button>
        <el-button
          v-permission="validateButtonPermission(route, 7)"
          type="success"
          @click="exportTable">
          导出表格
        </el-button>
        <span class="totalPayPrice">累计-提货应付款：{{ totalPayPrice || 0 }} 元</span>
      </div>
    </el-card>
    <!-- 查看 -->
    <View
      ref="viewRef"
      :rowData="rowData" />
    <!-- 新增修改 -->
    <Edit
      ref="editRef"
      :rowData="rowData"
      @save="save" />
    <!-- 生成提货单弹窗 -->
    <selectLadingBillTemplate
      :selectIds="selectIds"
      ref="selectDialogRef" />
  </div>
  <!-- 手机端页面 -->
  <H5Index v-else></H5Index>
</template>

<script setup>
import { ref, onMounted, watch } from "vue";
import Pagination from "@/components/Pagination.vue"
import Table from "@/components/Table.vue"
import ApiCapitalWareHouse from "@/api/modules/capital-ware-house"
import ApiTrainPickRecord from "@/api/modules/train-pickRecord"
import { useTable } from "@/hooks/useTable"
import View from "./component/View.vue"
import Edit from "./component/Edit.vue"
import message from "@/common/element-plus/message";
import config from "@/common/element-plus/config";
import app from "@/common/config/app";
import { validateButtonPermission } from "@/common/utils/validate";
import { useRoute } from "vue-router"
import { useAppStore } from "@/stores/app"
import { storeToRefs } from "pinia";
import selectLadingBillTemplate from "./component/selectLadingBillTemplate.vue";
import { formatDate } from "@/common/utils/date";
import ApiSysUser from "@/api/modules/sys-user"
import axios from "axios";
import H5Index from "./h5Index.vue";
import { ElMessageBox } from "element-plus";
import SearchCard from "@/components/SearchCard.vue"


const route = useRoute()
// 查询表单
const formData = ref({})
// 查看组件实例
const viewRef = ref()
// 新增修改组件实例
const editRef = ref()
// 生成提货单弹窗实例
const selectDialogRef = ref()
// 表格每行数据
const rowData = ref({})
//选择的数据的id集合
const selectIds = ref(null)
// 表格高度(固定表头)
const height = ref(0)
// 查询卡片实例
const searchCardRef = ref()
// 资金仓库下拉框
const capitalWareHouseList = ref([])
const capitalWareHouseLoading = ref(false)
// 主体公司下拉框
const baseCompanyList = ref([])
//收缩展开
const isExpand = ref(false);
const selectTime = ref([]);
const selectRows = ref(null);
//用户列表
const userList = ref([]);
//累计-提货应付款
const totalPayPrice = ref();

// 查询模板
const searchTemplate = ref([
  {
    label: "资金仓库名称",
    type: "simpleSelect",
    placeholder: "资金仓库名称",
    interfaceUrl: "baseCapitalWarehouse",
    value: "baseCapitalWarehouseId",
    isClosed: false,
  },

  {
    label: "提货日期",
    type: "daterange",
    value: "selectTime",
    isClosed: false,
  },
  {
    label: "启用状态",
    type: "status",
    placeholder: "启用状态",
    value: "isEnable",
    isClosed: false,
  }
]);

//token-请求头
const token = localStorage.getItem(localStorage.getItem("tokenName"))
const headers = ref({});
if (token) {
  headers.value["yg-token"] = token;
}

const { tableMethods, tableState, pagination } = useTable({
  fetchDataApi: async (data) => {
    const { pageSize, pageNum } = pagination
    const res = await ApiTrainPickRecord.selectPage(data, {
      pageNum: pageNum.value,
      pageSize: pageSize.value,
    })
    getSumPickPayPrice();
    return {
      list: res.data.records,
      total: res.data.total
    }
  }
})
const { getList } = tableMethods
const { pageSize, pageNum } = pagination
const { total, tableLoading, tableData } = tableState

//修改是否启用状态
const changeState = (newVal, row) => {
  ElMessageBox.confirm("确定要修改启用状态吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    const params = {
      id: row.id,
      isEnable: newVal
    }
    await ApiTrainPickRecord.changeState(params)
  }).catch(() => {
    row.isEnable = !newVal;
  });
}


//资金仓库列表
const getCapitalWareHouseSimpleNameList = async () => {
  capitalWareHouseLoading.value = true
  const data = await ApiCapitalWareHouse.getSimpleNameList("/baseCapitalWarehouse/")
  capitalWareHouseList.value = data.data
  capitalWareHouseLoading.value = false
}
getCapitalWareHouseSimpleNameList();

//主体公司列表
const getBaseCompanyList = async () => {
  const data = await ApiCapitalWareHouse.getSimpleNameList("/baseCompany/")
  baseCompanyList.value = data.data
}
getBaseCompanyList();

//获取用户列表
const getUserList = async () => {
  const pagination = {
    pageNum: 1,
    pageSize: -1
  }
  const res = await ApiSysUser.selectPage(null, pagination)
  userList.value = res.data.records;
}
getUserList();

// 处理选中行变化
const handleSelectionChange = async (rows) => {
  if (rows.length > 0) {
    selectIds.value = rows.map(item => item.id);
    selectRows.value = rows;
  } else {
    selectIds.value = null;
    selectRows.value = null;
  }
};

const getSumPickPayPrice = async () => {
  const params = {
    pickUserId: formData.value.pickUserId,
    baseCompanyId: formData.value.baseCompanyId,
    baseCapitalWarehouseId: formData.value.baseCapitalWarehouseId,
    startPickDate: formData.value.startPickDate,
    endPickDate: formData.value.endPickDate
  }
  const res = await ApiTrainPickRecord.getSumPickPayPrice(params);
  totalPayPrice.value = res.data
}

//导出表格
const exportTable = async () => {
  ElMessageBox.confirm("确定要导出表格吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    const params = {
      pickUserId: formData.value.pickUserId || "",
      baseCompanyId: formData.value.baseCompanyId || "",
      baseCapitalWarehouseId: formData.value.baseCapitalWarehouseId || "",
      startPickDate: formData.value.startPickDate || "",
      endPickDate: formData.value.endPickDate || ""
    }

    //先判断是否有数据能够导出
    const res = await axios.post(`${import.meta.env.VITE_API}/trainPickRecord/export`, params, {
      responseType: "application/json",
      headers: {
        "yg-token": token  // 根据后端要求设置 Token 头部
      }
    });
    if (!res.data.includes("message")) {
      const response = await axios.post(`${import.meta.env.VITE_API}/trainPickRecord/export`, params, {
        responseType: "blob", // 指定响应类型为 Blob
        headers: {
          "yg-token": token  // 根据后端要求设置 Token 头部
        }
      });
      const contentDisposition = response.headers["content-disposition"];
      let fileName = "文件.xlsx";
      if (contentDisposition && contentDisposition.includes("filename=")) {
        fileName = contentDisposition
          .split("filename=")[1]
          .split(";")[0]
          .replace(/['"]/g, "");
        fileName = decodeURIComponent(fileName)
      }

      const blob = new Blob([response.data], {
        type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
      });

      const link = document.createElement("a");
      link.href = URL.createObjectURL(blob);
      link.download = fileName;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      URL.revokeObjectURL(link.href);
    } else {
      message.warning("导出的数据为空")
    }
  })
}
// 监听时间选择
watch(() => selectTime.value, (newVal) => {
  if (newVal) {
    if (Array.isArray(newVal) && newVal.length === 2) {
      formData.value.startPickDate = newVal[0];
      formData.value.endPickDate = newVal[1];
    }
  } else {
    formData.value.startPickDate = "";
    formData.value.endPickDate = "";
  }
}, { immediate: true })
// 重置
const reset = () => {
  formData.value = {}
  selectTime.value=""
  getList()
}

// 打开查看对话框
const viewEvent = (row) => {
  viewRef.value.visibility = true
  rowData.value = row
}

// 打开新增对话框
const getBillLading = () => {
  if (!selectIds.value) {
    message.warning("请至少选择一条数据!");
    return;
  }
  selectDialogRef.value.visibility = true
}

// 保存后回调
const save = async () => {
  editRef.value.visibility = false
  message.success()
  // await getList()
}

// 监听查询卡片大小变化
const resizeObserver = new ResizeObserver(entries => {
  for (const entry of entries) {
    if (contentFullScreen.value) {
      height.value = (window.innerHeight - app.otherHeight - app.tagHeight - entry.contentRect.height) + "px"
    } else {
      height.value = (window.innerHeight - app.otherHeight - app.tagHeight - app.headerHeight - entry.contentRect.height) + "px"
    }
  }
})

const appStore = useAppStore()

// 保持响应式
const { contentFullScreen } = storeToRefs(appStore)

onMounted(() => {
  if (appStore.isPhone) return
  resizeObserver.observe(searchCardRef.value.$el)
})
</script>

<style lang="scss" scoped>
.train_pick_up_record {
  .search_card {
    margin-bottom: 4px;

    :deep(.el-card__body) {
      padding: 10px;
      display: flex;
      justify-content: space-between;
    }

    .el-button {
      margin: 5px 10px 5px 0;
    }

    .el-form-item {
      margin-right: 10px;
      padding: 5px 0;
    }
  }

  .table_card {
    :deep(.el-card__body) {
      padding: 0;
    }
  }

  // :deep(.cell){
  //   white-space: nowrap;
  //   overflow: hidden;
  //   text-overflow: ellipsis;
  // }
  :deep(.el-card__body) {
    position: relative;
  }

  .btn-bottom {
    position: absolute;
    bottom: 10px;
    left: 5px;
  }

  .expanded {
    user-select: none;
    margin-right: 10px;
    text-align: right;
    color: #e6a23c;
    width: 42px;
    margin-top: 0px;

    span {
      font-size: 14px;
    }
  }

  .expanded:hover {
    cursor: pointer;
  }

  .el-form-item {
    margin-right: 20px !important;
  }

  .totalPayPrice {
    margin-left: 30px;

  }
}
</style>
